package com.lissic.lng.dao;

import java.io.UnsupportedEncodingException;

import org.apache.http.Header;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;

import com.lissic.lng.entity.LNG;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;


public class LngDaoImpl implements ILngDao {
	
	private AsyncHttpClient client ;
	private RequestParams params;
	private Context context;
	private Handler handler;
	private String url="http://192.168.191.1:8888/LngWebService1/LNGService";
	private String username;
	public LngDaoImpl(Context context,String username,Handler handler){
		this.context = context;
		this.username = username;
		this.handler = handler;
	}
	@Override
	public int addLngData(LNG lng) {
		//实现添加lng气瓶数据的逻辑
		client = new AsyncHttpClient();
		params = new RequestParams();
		params.add("username", username);
		params.add("lngid", lng.getId()+"");
		params.add("lngyw", lng.getYw());
		params.add("lngyl", lng.getYl());
		params.add("lngzkd", lng.getZkd());
		params.add("lngqhl", lng.getQhl());
		params.add("lngjqcs", lng.getJqcs());
System.out.println(username);
		//检测网络是否连接
		ConnectivityManager connect  = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connect.getActiveNetworkInfo();
		if(info!=null){
			boolean connected = info.isConnected();
			if(connected){
				client.post(url, params, new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
						try {
							String content = new String(responseBody,"gbk");
							Message msg = Message.obtain();
							if(statusCode==200){
								if(content.equals("添加成功")){
									msg.obj = "success";
								}else if(content.equals("添加失败")){
									msg.obj = "fail";
								}
							}
							handler.sendMessage(msg);
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}
					
					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
					}
				});
			}else{
				Message msg = Message.obtain();
				msg.obj = "disconnect";
				handler.sendMessage(msg);
			}
		}else{
			Message msg = Message.obtain();
			msg.obj = "disconnect";
			handler.sendMessage(msg);
		}
		return 0;
	}

	@Override
	public int deleteLngData(int lng_id) {
		//实现删除lng气瓶数据的逻辑
		return 0;
	}

	@Override
	public int updateLngData(LNG lng) {
		//实现更新lng气瓶数据的逻辑
		return 0;
	}

	@Override
	public LNG queryLngData(int lng_id) {
		//实现查询lng气瓶数据的逻辑
		return null;
	}

}
